package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.OSSUplodFile;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SpringContextUtil;
import com.ruoyi.system.aikeService.ToZhtcApiService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.bo.ZsyyChannelInfoAddBo;
import com.ruoyi.system.bo.ZsyyChannelInfoQueryBo;
import com.ruoyi.system.bo.ZsyyChannelInfoEditBo;
import com.ruoyi.system.domain.ZsyyChannelInfo;
import com.ruoyi.system.mapper.ZsyyChannelInfoMapper;
import com.ruoyi.system.vo.ZsyyChannelInfoVo;
import com.ruoyi.system.service.IZsyyChannelInfoService;

import javax.servlet.ServletException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 通道管理Service业务层处理
 *
 * @author wangghua
 * @date 2021-07-14
 */
@Service
public class ZsyyChannelInfoServiceImpl extends ServicePlusImpl<ZsyyChannelInfoMapper, ZsyyChannelInfo> implements IZsyyChannelInfoService {

    @Autowired
    private ZsyyChannelInfoMapper iZsyyChannelInfoMapper;
    @Autowired
    private ToZhtcApiService toZhtcApiService;
	@Autowired
	private GetCommunityIdImpl getCommunityIdImpl;

    @Override
    public ZsyyChannelInfoVo queryById(Long id){
        return getVoById(id, ZsyyChannelInfoVo.class);
    }

    @Override
    public TableDataInfo<ZsyyChannelInfoVo> queryPageList(ZsyyChannelInfoQueryBo bo) {
		Page<ZsyyChannelInfoVo> page = iZsyyChannelInfoMapper.queryPageList(PageUtils.buildPage(),bo);
		return PageUtils.buildDataInfo(page);
    }

    @Override
    public List<ZsyyChannelInfoVo> queryList(ZsyyChannelInfoQueryBo bo) {
        return listVo(buildQueryWrapper(bo), ZsyyChannelInfoVo.class);
    }

    private LambdaQueryWrapper<ZsyyChannelInfo> buildQueryWrapper(ZsyyChannelInfoQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZsyyChannelInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getParkCode()), ZsyyChannelInfo::getParkCode, bo.getParkCode());
        lqw.eq(bo.getCommunityId() != null, ZsyyChannelInfo::getCommunityId, bo.getCommunityId());
        lqw.eq(bo.getEntranceType() != null, ZsyyChannelInfo::getEntranceType, bo.getEntranceType());
        lqw.eq(bo.getEnable() != null, ZsyyChannelInfo::getEnable, bo.getEnable());
        return lqw;
    }

    @Override
    public Boolean insertByAddBo(ZsyyChannelInfoAddBo bo) {
        ZsyyChannelInfo add = BeanUtil.toBean(bo, ZsyyChannelInfo.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(ZsyyChannelInfoEditBo bo) {
        ZsyyChannelInfo update = BeanUtil.toBean(bo, ZsyyChannelInfo.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }
	@Override
	public List<ZsyyChannelInfoVo> channelList(ZsyyChannelInfoQueryBo bo) {
		bo.setCommunityId(getCommunityIdImpl.getLoginUser().getCommunityId());
		bo.setEnable(1);
		return listVo(buildQueryWrapper(bo), ZsyyChannelInfoVo.class);
	}
    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(ZsyyChannelInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

	public JSONObject getToken() throws ServletException, IOException {
		String result = null;
		try {
			//创建默认连接
			CloseableHttpClient httpClient = HttpClients.createDefault();
			//创建HttpGet对象,处理get请求,转发到A站点
			HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx4250bfd6f75fd83c&secret=0417653972a45ba7ed2f8a2a4a166775");
			//执行
			CloseableHttpResponse response = httpClient.execute(httpGet);
			int code = response.getStatusLine().getStatusCode();
			//获取状态
			System.out.println("http请求结果为:"+code);
			if(code == 200){
				//获取A站点返回的结果
				result = EntityUtils.toString(response.getEntity());
//                System.out.println(result);
				//把结果返回给B站点
			}
			response.close();
			httpClient.close();
		} catch (Exception e) {
		}
		return JSONObject.parseObject(result);
	}

	@Override
	public Map<String, Object> getQRcode(Map<String, String> map) throws ServletException, IOException {
		JSONObject getToken = this.getToken();
		Map<String, Object> data = new HashMap<>();
		String url = null;
		Long id =null;
		Integer type =null;
		try {
			//创建默认连接
			String token = getToken.getString("access_token");
			String path = null;
			/*if(map.containsKey("access_token")){
				token = map.get("access_token").toString();
			}*/
			if(map.containsKey("path")){
				path = map.get("path").toString();
			}
			if(map.containsKey("id")){
				id = Long.parseLong(map.get("id"));
			}
			if(map.containsKey("type")){
				type = Integer.parseInt(map.get("type"));
			}
			JSONObject json = new JSONObject();
			json.put("path",path);
			String params= String.valueOf(json);
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost =new HttpPost("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="+token);
			//创建HttpGet对象,处理get请求,转发到A站点
			httpPost.setHeader("Accept", "application/json");    //接收报文类型
			httpPost.setHeader("Content-Type", "application/json");   //发送报文类型
			if(params != null && !"".equals(params)){
				StringEntity entity = new StringEntity(params, "UTF-8");
				httpPost.setEntity(entity);
			}
			//执行
			CloseableHttpResponse response = httpClient.execute(httpPost);
			int code = response.getStatusLine().getStatusCode();
			//获取状态
			System.out.println("http请求结果为:"+code);
			if(code  == 200){
				HttpEntity responseEntity = response.getEntity();
				InputStream in =  responseEntity.getContent();
				url = OSSUplodFile.inputUplaod(in);
				ZsyyChannelInfo channelInfo = iZsyyChannelInfoMapper.selectById(id);
				if (type==0){
					channelInfo.setEnterQrCode(url);
				}else if (type==1){
					channelInfo.setPayQrCode(url);
				}else if (type==2){
					channelInfo.setPrePayQrCode(url);
				}
				iZsyyChannelInfoMapper.updateById(channelInfo);
				//把结果返回给B站点
			}
			data.put("url", url);
			data.put("code", 0);
			data.put("msg", "成功");
			response.close();
			httpClient.close();
		} catch (Exception e) {
		}
		return data;
	}

	@Override
	public String controlCha(Map<String, String> map) {
		Long id =null;
		Integer opType =null;
		if(map.containsKey("id")){
			id = Long.parseLong(map.get("id"));
		}
		if(map.containsKey("opType")){
			opType = Integer.parseInt(map.get("opType"));
		}
		LoginUser loginUser = SecurityUtils.getLoginUser();
		ZsyyChannelInfo channelInfo = iZsyyChannelInfoMapper.selectById(id);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map m = new HashMap();
		m.put("parkCode",channelInfo.getParkCode());
		m.put("channelCode",channelInfo.getChannelCode());
		m.put("operator",loginUser.getUser().getNickName());
		m.put("operateTime",sdf.format(new Date()));
		m.put("opType",opType);
		toZhtcApiService.privateApi("opGate", JSON.toJSONString(m),null);
		return "OK";
	}



}
